package com.facebook.swift.codec.metadata;

import com.google.common.base.Predicate;

public class PatternFilter implements Predicate<String> {
	public final String pattern;
	private boolean startsWithAsTrue;
	public PatternFilter(String pattern) {
		this(pattern,true);
	}
	public PatternFilter(String pattern,boolean startsWithAsTrue) {
		super();
		this.pattern = pattern;
		this.startsWithAsTrue = startsWithAsTrue;
	}
	@Override
	public boolean apply(String input) {
		if(startsWithAsTrue && input.startsWith(pattern)){
			return true;
		}else	if(input.matches(pattern)){
			return true;
		}else if(pattern.indexOf('*') >= 0 && input.matches(pattern.replaceAll("\\*+", "\\\\S*"))){
			return true;
		}else if(pattern.indexOf('?') >= 0 && input.matches(pattern.replaceAll("\\?", "\\\\S"))){
			return true;
		}
		return false;
	}
	public static boolean filter(String pattern,String input){
		return new PatternFilter(pattern).apply(input);
	}
	public static boolean filter(String pattern,String input,boolean startsWithAsTrue){
		return new PatternFilter(pattern,startsWithAsTrue).apply(input);
	}
}
